package com.demo2.todo.service.impl;

import com.demo2.todo.model.dto.CommentRequest;
import com.demo2.todo.model.dto.CommentResponse;
import com.demo2.todo.model.entity.Comment;
import com.demo2.todo.model.entity.ShareTodo;
import com.demo2.todo.model.entity.Todo;
import com.demo2.todo.model.entity.User;
import com.demo2.todo.exception.BadRequestException;
import com.demo2.todo.exception.ResourceNotFoundException;
import com.demo2.todo.repository.CommentRepository;
import com.demo2.todo.repository.ShareTodoRepository;
import com.demo2.todo.repository.TodoRepository;
import com.demo2.todo.repository.UserRepository;
import com.demo2.todo.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author evi
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {
    private final CommentRepository commentRepository;
    private final ShareTodoRepository shareTodoRepository;
    private final UserRepository userRepository;
    private final TodoRepository todoRepository;

    @Override
    @Transactional(readOnly = true)
    public List<CommentResponse> getCommentsByTodoId(Long todoId) {
        // 移除用户验证，允许所有人查看评论
        List<Comment> rootComments = commentRepository.findByTodoIdAndParentIdIsNull(todoId);
        return rootComments.stream()
                .map(this::buildCommentTree)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public CommentResponse createComment(CommentRequest request, User user) {
        Todo todo = todoRepository.findById(request.getTodoId())
                .orElseThrow(() -> new ResourceNotFoundException("待办事项不存在"));

        Comment comment = new Comment();
        comment.setContent(request.getContent());
        comment.setUserId(user.getId());
        comment.setTodoId(todo.getId());
        comment.setParentId(request.getParentId());

        Comment saved = commentRepository.save(comment);
        return mapToDto(saved);
    }


    // 构建评论树
    private CommentResponse buildCommentTree(Comment comment) {
        CommentResponse response = mapToDto(comment);
        // 查询子评论
        List<Comment> children = commentRepository.findByParentIdOrderByCreatedAt(comment.getId());
        if (!children.isEmpty()) {
            response.setChildren(children.stream()
                    .map(this::buildCommentTree)
                    .collect(Collectors.toList()));
        }
        return response;
    }

    private CommentResponse mapToDto(Comment comment) {
        CommentResponse response = new CommentResponse();
        response.setId(comment.getId());
        response.setTodoId(comment.getTodoId());
        response.setUserId(comment.getUserId());
        response.setContent(comment.getContent());
        response.setParentId(comment.getParentId());
        response.setCreatedAt(comment.getCreatedAt());

        // 设置用户名
        userRepository.findById(comment.getUserId()).ifPresent(
                user -> response.setUsername(user.getUsername())
        );

        return response;
    }
}